<template>
  <div class="dishes-container">
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索菜品名称"
            clearable
            @clear="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-row :gutter="20" class="dishes-list">
      <el-col :span="6" v-for="dish in dishes" :key="dish.dishId">
        <transition name="dish-fade" appear>
          <el-card
            :body-style="{ padding: '0px' }"
            class="dish-card"
            @click="goToDishDetail(dish.dishId!)"
          >
            <div class="dish-image-container">
              <img
                :src="getImageUrl(dish.dishImage || '')"
                class="dish-image"
                @error="handleImageError"
              />
              <div class="dish-overlay">
                <el-tag v-if="dish.dishStatus === '1'" type="danger" size="large">停售</el-tag>
              </div>
            </div>
            <div class="dish-info">
              <div class="dish-header">
                <h3 class="dish-name">{{ dish.dishName }}</h3>
                <el-tag size="small" effect="plain">{{ dish.dishType }}</el-tag>
              </div>
              <p class="dish-description">{{ dish.dishDescription || '暂无描述' }}</p>
              <div class="dish-footer">
                <div class="price-section">
                  <span class="price">¥{{ dish.dishPrice }}</span>
                  <span class="sales-count">已售 {{ dish.salesCount || 0 }}</span>
                </div>
                <el-button
                  type="primary"
                  size="small"
                  :icon="ShoppingCart"
                  :disabled="dish.dishStatus === '1'"
                  @click.stop="quickAddToCart(dish)"
                >
                  加入购物车
                </el-button>
              </div>
            </div>
          </el-card>
        </transition>
      </el-col>
    </el-row>

    <el-empty v-if="dishes.length === 0 && !loading" description="暂无菜品数据" />

    <div v-loading="loading" class="loading-overlay" v-if="loading"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Search, ShoppingCart } from '@element-plus/icons-vue';
import { getAllDishes, getDishesByName } from '@/api/dish';
import { useCartStore } from '@/stores/cart';
import { useUserStore } from '@/stores/user';
import type { Dish } from '@/types';
import { ElMessage } from 'element-plus';

const router = useRouter();
const cartStore = useCartStore();
const userStore = useUserStore();

const dishes = ref<Dish[]>([]);
const searchKeyword = ref('');
const loading = ref(false);

// 加载所有菜品
const loadDishes = async () => {
  loading.value = true;
  try {
    const response = await getAllDishes();
    if (response.operateResult === 'SUCC' && response.data) {
      dishes.value = response.data;
    } else {
      dishes.value = [];
    }
  } catch (error) {
    ElMessage.error('加载菜品失败');
    dishes.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索菜品
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    await loadDishes();
    return;
  }
  
  loading.value = true;
  try {
    const response = await getDishesByName(searchKeyword.value);
    if (response.operateResult === 'SUCC' && response.data) {
      dishes.value = response.data;
    } else {
      dishes.value = [];
    }
  } catch (error) {
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
};

// 跳转到菜品详情
const goToDishDetail = (dishId: number) => {
  router.push(`/user/dish/${dishId}`);
};

// 快速加入购物车
const quickAddToCart = async (dish: Dish) => {
  if (!userStore.userId) {
    ElMessage.warning('请先登录');
    return;
  }
  
  if (dish.dishStatus === '1') {
    ElMessage.warning('该菜品已停售');
    return;
  }
  
  await cartStore.addItem(userStore.userId, dish.dishId!, 1);
};

// 图片加载错误处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://via.placeholder.com/300x200?text=No+Image';
};

// 获取图片URL
const getImageUrl = (imagePath: string) => {
  if (!imagePath) return 'https://via.placeholder.com/300x200?text=No+Image';
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  return `http://localhost:8060${imagePath}`;
};

onMounted(() => {
  loadDishes();
});
</script>

<style scoped>
.dishes-container {
  min-height: calc(100vh - 100px);
  position: relative;
}

.search-card {
  margin-bottom: 20px;
  animation: slideDown 0.5s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.dishes-list {
  margin-top: 20px;
}

.dish-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
}

.dish-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.dish-fade-enter-active {
  animation: dishFadeIn 0.5s ease-out;
}

@keyframes dishFadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.dish-image-container {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.dish-card:hover .dish-image {
  transform: scale(1.1);
}

.dish-overlay {
  position: absolute;
  top: 10px;
  right: 10px;
}

.dish-info {
  padding: 15px;
}

.dish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.dish-name {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 10px;
}

.dish-description {
  color: #909399;
  font-size: 14px;
  margin: 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 40px;
}

.dish-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.price-section {
  display: flex;
  flex-direction: column;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}

.sales-count {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 10;
}
</style>
